package dnl.proj.rami;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Daniel Orr
 */
public class Conversion1 implements StringConversion {
    @Override
    public String convert(String s) {
        String[] lines = StringUtils.split(s, "\n\r");
        List<String[]> outLines = new ArrayList<>();// result lines
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            String[] words = StringUtils.split(s, " ");
            words = reverseWords(words);
            ArrayUtils.reverse(words);

            outLines.add(words);
        }

        for (int i = 0; i < outLines.size(); i++) {
            String[] line = outLines.get(i);
            if (i > outLines.size() - 1) {
                String[] nextLine = outLines.get(i + 1);
                String swap = line[line.length - 1];
                line[line.length - 1] = nextLine[0];
                nextLine[0] = swap;
            }
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < outLines.size(); i++) {
            if (i > 0) {
                sb.append("\n");
            }
            String[] line = outLines.get(i);
            for (int j = 0; j < line.length; j++) {
                if (j > 0) {
                    sb.append(" ");
                }
                sb.append(line[j]);
            }
        }

        return sb.toString();
    }

    static String[] reverseWords(String[] words) {
        List<String> result = new ArrayList<>();
        for (int i = 0; i < words.length; i++) {
            result.add(StringUtils.reverse(words[i]));
        }
        return result.toArray(new String[result.size()]);
    }
}
